package dao.Impl;

import dao.BlogDao;
import entity.Blog;
import handler.CustomBeanBlogListHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.C3p0Helper;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.List;

public class BlogDaoImpl implements BlogDao {
    @Override
    public List<Blog> findAll() {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql ="select * from blog";
        try {
            return qr.query(sql,new CustomBeanBlogListHandler());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Blog findById(int id) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "select * from blog where id=?";
        try {
            return qr.query(sql, new BeanHandler<>(Blog.class), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void save(Blog blog) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "insert into blog(actionTime,address,peoples,event,title) values(?,?,?,?,?)";
        try {
            qr.update(sql,blog.getActionTime(),blog.getAddress(),blog.getPeoples(),blog.getEvent(),blog.getTitle());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void update(Blog blog) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "update blog set actionTime=?,address=?,peoples=?,event=?,title=? where id=?";
        try {
            qr.update(sql,blog.getActionTime(),blog.getAddress(),blog.getPeoples(),blog.getEvent(),blog.getTitle(),blog.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void delete(int id) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "delete from blog where id=?";
        try {
            qr.update(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Blog> findByTime(String time) {
        QueryRunner qr = new QueryRunner(C3p0Helper.getDataSource());
        String sql = "select * from blog where actionTime=?";
        try {
            return qr.query(sql,new BeanListHandler<>(Blog.class),time);
            //return qr.query(sql,new CustomBeanBlogListHandler(),time);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
